package org.interfaceadaptation.parameter.expression.impl;

import org.interfaceadaptation.parameter.expression.Context;
import org.interfaceadaptation.util.ReflectionUtils;

public class BranchProperty extends LeafProperty {

	public BranchProperty(AbstractExpression expression, String propertyName) {
		super(expression, propertyName);
	}

	@Override
	public Object getValue(Context context) {
		Object baseValue = getParent().getValue(context);
		Object currentPropValue = super.getValue(context);

		if (currentPropValue == null) {
			currentPropValue = createAndSetDefaultCurrentPropValue(baseValue);
		}
		return currentPropValue;
	}

	private Object createAndSetDefaultCurrentPropValue(Object baseValue) {
		Object currentPropValue;
		currentPropValue = ReflectionUtils.newInstance(getReturnType());
		ReflectionUtils.invokePropertySetter(getPropertyDescriptor(),
				baseValue, currentPropValue);
		return currentPropValue;
	}
	
}
